import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Checkbox,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Tree
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './List.less';

const { TreeNode } = Tree;
const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
/* eslint react/no-multi-comp:0 */
@connect(({ user, loading }) => ({
  user,
  loading: loading.models.user,
}))

@Form.create()
    class UpdateForm extends PureComponent {
      constructor(props) {
        super(props);
        this.state = {
          formVals: {
            id:'',
            name: '',
            permissions:[],
            select_permission:[],
          },
          permission:[],
          currentStep: 0,
          expandedKeys: [],
          autoExpandParent: true,
          checkedKeys: [],
          selectedKeys: [],
        };
    
        this.formLayout = {
          labelCol: { span: 7 },
          wrapperCol: { span: 13 },
        };
      }

      componentDidMount() {
        const { dispatch } = this.props;
        dispatch({
          type: 'user/fetchPermission',
        });
      }
    
      handleNext = currentStep => {
        const { form, handleUpdate } = this.props;
        const { formVals: oldValue } = this.state;
        form.validateFields((err, fieldsValue) => {
          if (err) return;
          const formVals = { ...oldValue, ...fieldsValue };
          this.setState(
            {
              formVals,
            },
            () => {
              if (currentStep < 1) {
                this.forward();
              } else {
                formVals.id = this.props.values.id
                handleUpdate(formVals);
                this.setState({
                  currentStep:0
                });
              }
            }
          );
        });
      };

      backward = () => {
        const { currentStep } = this.state;
        this.setState({
          currentStep: currentStep - 1,
        });
      };
    
      forward = () => {
        const { currentStep } = this.state;
        this.setState({
          currentStep: currentStep + 1,
        });
      };

      onExpand = (expandedKeys) => {
        console.log('onExpand', expandedKeys);
        // if not set autoExpandParent to false, if children expanded, parent can not collapse.
        // or, you can remove all expanded children keys.
        this.setState({
          expandedKeys,
          autoExpandParent: false,
        });
      }
    
      onCheck = (checkedKeys) => {
        this.setState({ 
          ...this.state,
          checkedKeys:checkedKeys,
          formVals:{
            ...this.state.formVals,
            select_permission:checkedKeys
          },
        });
      }
    
      onSelect = (selectedKeys, info) => {
        console.log('onSelect', info);
        this.setState({ selectedKeys });
      }
    
      renderTreeNodes = data => data.map((item) => {
        if (item.children) {
          return (
            <TreeNode title={item.name} key={item.id} dataRef={item}>
              {this.renderTreeNodes(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode title={item.name} key={item.id} dataRef={item} />;
      })
    
      renderContent = (currentStep, formVals) => {
        const { form } = this.props;
        let defaultCheckedKeys = this.props.values.permission?this.props.values.permission:[];
        if (currentStep === 1) {
          return [
            <FormItem {...this.formLayout} label="权限">
            {form.getFieldDecorator("permissions", {
                initialValue:defaultCheckedKeys
              })(
                <Tree
                  checkable
                  onExpand={this.onExpand}
                  expandedKeys={this.state.expandedKeys}
                  autoExpandParent={this.state.autoExpandParent}
                  onCheck={this.onCheck}
                  defaultCheckedKeys={defaultCheckedKeys}
                  onSelect={this.onSelect}
                  selectedKeys={this.state.selectedKeys}
                >
                  {this.renderTreeNodes(this.state.permission)}
                </Tree>
                )}
            </FormItem>
          ];
        }
        return [
          <FormItem {...this.formLayout} label="名称">
            {form.getFieldDecorator('name', {
              rules: [{ required: true, message: '请输入名称！'}],
              initialValue: this.props.values.name,
            })(
              <Input placeholder="请输入" />
          )}
          </FormItem>,
        ];
      };
    
      renderFooter = currentStep => {
        const { handleUpdateModalVisible } = this.props;
        if (currentStep === 1) {
          return [
            <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
              上一步
            </Button>,
            <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
              取消
            </Button>,
            <Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)}>
              完成
            </Button>,
          ];
        }
        return [
          <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
            取消
          </Button>,
          <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
            下一步
          </Button>,
        ];
      };
    
      render() {
        const { updateModalVisible, handleUpdateModalVisible, values } = this.props;
        const { currentStep, formVals } = this.state;
        const {
          user:{permission},
          loading,
        } = this.props;

        this.setState({
          permission,
        });

        return (
          <Modal
            width={640}
            bodyStyle={{ padding: '32px 40px 48px' }}
            destroyOnClose
            title="修改权限"
            visible={updateModalVisible}
            footer={this.renderFooter(currentStep)}
            onCancel={() => handleUpdateModalVisible()}
          >
            <Steps style={{ marginBottom: 28 }} size="small" current={currentStep}>
              <Step title="基本信息" />
              <Step title="设置权限" />
            </Steps>
            {this.renderContent(currentStep, formVals)}
          </Modal>
        );
      }
    }

/* eslint react/no-multi-comp:0 */
@connect(({ user, loading }) => ({
  user,
  loading: loading.models.user,
}))
@Form.create()
class Role extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
  };

  columns = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleUpdateModalVisible(true, record)}>修改</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleDelete(record)}>删除</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'user/fetchRole',
    });
  }

  handleDelete(record){
    const { dispatch } = this.props;
    dispatch({
      type: 'user/fetchDeleteRole',
      payload: {
        id:record.id
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'user/fetchRole',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'user/fetchRole',
      payload: {},
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'rule/remove',
          payload: {
            key: selectedRows.map(row => row.key),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'user/fetchRole',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      stepFormValues: record || {},
    });
  };

  handleUpdate = fields => {
    const { dispatch } = this.props;
    if(fields.id){
      dispatch({
        type: 'user/fetchUpdateRole',
        payload: {
          id: fields.id,
          name: fields.name,
          permission: fields.select_permission.length?fields.select_permission: fields.permissions,
        },
      });
    }else{
      dispatch({
        type: 'user/fetchAddRole',
        payload: {
          name: fields.name,
          permission: fields.select_permission.length?fields.select_permission: fields.permissions,
        },
      });
    }
    this.handleUpdateModalVisible();
  };

  render() {
    const {
      user:{role},
      loading,
    } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, stepFormValues } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
        <Menu.Item key="approval">批量审批</Menu.Item>
      </Menu>
    );

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    return (
      <PageHeaderWrapper title="角色列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleUpdateModalVisible(true, {})}>
                新建
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button>批量操作</Button>
                  <Dropdown overlay={menu}>
                    <Button>
                      更多操作 <Icon type="down" />
                    </Button>
                  </Dropdown>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={{list:role}}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        {/* <CreateForm {...parentMethods} modalVisible={modalVisible} /> */}
          <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={stepFormValues}
          />
      </PageHeaderWrapper>
    );
  }
}

export default Role;
